package com.ryan.ohos.extension.util;

import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.miscservices.wallpaper.WallpaperController;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import static ohos.miscservices.wallpaper.WallpaperController.WALLPAPER_SYSTEM;

/**
 * ApplyWallpaperAsyncTask
 *
 * @since 2021.07.20
 */
public class ApplyWallpaperAsyncTask {

    private final Context context;
    private final File imageFile;
    private TaskDispatcher taskDispatcher;
    private ApplyWallpaperListener applyWallpaperListener;

    /**
     * ApplyWallpaperAsyncTask Instance
     *
     * @param context 上下文
     * @param imageFile 壁纸文件
     * @param applyWallpaperListener 壁纸设置状态回调监听
     */
    public ApplyWallpaperAsyncTask(Context context, File imageFile, ApplyWallpaperListener applyWallpaperListener) {
        this.context = context;
        this.imageFile = imageFile;
        this.applyWallpaperListener = applyWallpaperListener;
    }

    private boolean doBackground() {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(imageFile);
            WallpaperController.getInstance(context).setWallpaper(inputStream, WALLPAPER_SYSTEM);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    private void onPostExecute(boolean isSuccess) {
        if (applyWallpaperListener != null) {
            applyWallpaperListener.onApplyWallpaperSucceed(isSuccess);
        }
    }

    /**
     * 执行线程
     */
    public void execute() {
        if (taskDispatcher == null) {
            taskDispatcher = context.createParallelTaskDispatcher("save", TaskPriority.DEFAULT);
        }

        taskDispatcher.asyncDispatch(() -> {
            boolean result = doBackground();
            onPostExecute(result);
        });
    }

    /**
     * setApplyWallpaperListener
     *
     * @param applyWallpaperListener 设置状态回调监听
     */
    public void setApplyWallpaperListener(ApplyWallpaperListener applyWallpaperListener) {
        this.applyWallpaperListener = applyWallpaperListener;
    }

    /**
     * ApplyWallpaperListener
     */
    public interface ApplyWallpaperListener {
        /**
         * onApplyWallpaperSucceed
         *
         * @param isSuccess 设置壁纸回调,true:设置壁纸成功;false:设置壁纸失败
         */
        void onApplyWallpaperSucceed(boolean isSuccess);
    }
}
